<template>
	<view class="calendar-component">
		<!-- 年月份、左右切换按钮 -->
		<view class="date-year-month">
			<slot class="prevBtn" name="prevMonth"></slot>
			<text>{{currentYear}}年{{currentMonth}}月</text>
			<slot class="nextBtn" name="nextMonth"></slot>
		</view>
		<view>
			<!-- 日历表头 -->
			<view class="calendar-header" :style="{'background-color':calendarThemeColor}">
				<view class="layout-flex row">
					<text class="date-week" 
						:style="'width:'+(systemInfo.windowWidth/7-10)+'px;height:20px'" 
						v-for="(item,index) in weekStr" 
						:key="index">
			<text>{{item}}</text>
					</text>
				</view>
			</view>
			<!-- 日历内容 -->
			<view class="layout-flex row" style="flex-wrap: wrap;">
				<view class="date-day" 
					:class="[item.day <= 0 ?'bgwhite unavailable':item.class, {'active':activeDateIndex == item.day}]"
					:style="{
						width:(systemInfo.windowWidth/7-1) +'px',
					  height:'98rpx',
						backgroundColor: activeDateIndex == item.day?calendarThemeColor:''}"
					:data-year="currentYear" 
					:data-month="currentMonth" 
					:data-day="item.day" 
					:data-amount="item.amount" 
					:data-stock="item.stock" 
					:data-index="index" 
					:data-date-class="item.day <= 0 ?'unavailable ':item.class" 
					@click="_onPressDateEvent" 
					v-for="(item,index) in days" 
					:key="index"
				>
					<!-- 日历上的文本内容：价格和库存 -->
					<view class='item-days'>
						<text>{{item.day>0?(item.daytext?item.daytext:item.day):''}}</text>
						<text class='amount' v-if='item.day>0 && item.amount >0'>¥{{item.amount}}</text>
						<!-- <text class='total-stock' v-if='item.day>0 && item.stock >0'>总：{{item.stock}}</text> -->
						<text class="stock" :style="{color: activeDateIndex == item.day?'':calendarThemeColor}" v-if='item.day>0 && item.stock >0 && item.sold>=0'>余：{{item.stock - item.sold}}</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	/**
	 * @desc 获取当前加载时间
	 * @var {number} DATE_YEAR - 当前年
	 * @var {number} DATE_MONTH - 当前月
	 * @var {number} DATE_DAY - 当前日
	 */
	const DATE_YEAR = new Date().getFullYear();
	const DATE_MONTH = new Date().getMonth() + 1;
	const DATE_DAY = new Date().getDate();
	import { _getDateFormat, _getTimeStamp, _getTotalDayByMonth, _getWeek,_getTimeYear,_getTimeMonth,_getTimeDay} from '@/utils/DateFun'
	export default {
		props:{
		/**
			* priceList            带有价格库存的数组
			* currentYear          当前显示的年
			* currentMonth         当前显示的月
			* currentDay           当前显示的日
			* priceTagName         后台接口价格的字段名
			* stockTagName         后台接口库存的字段名
			* soldTagName          后台接口销量的字段名
			* stateTypeName        后台接口库存状态的字段名
			* canChooseDate        加载的日历是否可点击选中日期
			* startDateStamp       规定遍历日历的初始时间戳，初始日期前均不可选择
			* hightLightDate       当前选中的高亮日期
			* calendarThemeColor   日历的主题色，默认橙色 #FF9F00
			*/
			priceList:Array,
			currentYear: {
				type:Number,
				default:DATE_YEAR
			},
			currentMonth: {
				type:Number,
				default:DATE_MONTH
			},
			currentDay: {
				type:Number,
				default:DATE_DAY
			},
			priceTagName: {
				type: String,
				default: ''
			},
			stockTagName: {
				type: String,
				default: ''
			},
			soldTagName: {
				type: String,
				default: ''
			},
			stateTypeName: {
				type: String,
				default: ''
			},
			canChooseDate: {
				type: Boolean,
				default: true
			},
			startDateStamp:{
				type: Number,
				default: 0
			},
			hightLightDate: {
				type: Number,
				default: 0
			},
			calendarThemeColor:{
				type:String,
				default:'#FF9F00'
			}
		},
		data() {
			return {
				/**
				* days          遍历日历的数组
				* systemInfo    手机配置信息
				* checkDateObj  选中的日期对象
				* startYear     规定遍历日历的初始年份
				* startMonth    规定遍历日历的初始月份
				* startDay      规定遍历日历的初始日
				* activeDateIndex  当前选中日期的index
				*/
				days: {},
				systemInfo: {},
				weekStr: ['日', '一', '二', '三', '四', '五', '六'],
				checkDateObj:{},
				startYear:0,
				startMonth:0,
				startDay:1,
				activeDateIndex:null
			};
		},
		watch:{
			/**
			 * @desc 监听价格库存数组是否有变化，及时更新数据
			 * @param {object[]} newpriceList - 更新后的价格日历数组
			 * @param {object[]} oldpriceList - 更新前的价格日历数组
			 */
			priceList:function(newpriceList,oldpriceList){
				this._createDateListData(this.currentYear, this.currentMonth);
			}
		},
		onReady:function(){
		// 在组件实例进入页面节点树时执行
			let _this = this;
			//获取手机配置，实现日期天数宽度适配
			uni.getSystemInfo({
				success: function (res) {
					_this.systemInfo = res
				}
			})
		},
		mounted:function(){
			this._handleInitialDateFun();
		},
		methods:{

			/**
			 * @method
			 * @desc 处理初始日期
			 * @var {number} startYear - 规定遍历日历的初始年份
			 * @var {number} startMonth - 规定遍历日历的初始月份
			 * @var {number} startDay - 规定遍历日历的初始日
			 * @var {number} startDateStamp - 规定遍历日历的初始时间戳
			 * @var {number} hightLightDate - 当前选中的高亮日期
			 */
			_handleInitialDateFun:function(){
				//如果没有规定起始日期，年月是本年本月，起始号是今天
				let startYear = this.currentYear;
				let startMonth = this.currentMonth;
				let startDay = this.currentDay;
				let startDateStamp = this.startDateStamp;
				let hightLightDate = this.hightLightDate;
				if (startDateStamp != 0) {
					//如果规定了遍历日历的起始日期，当前日历显示的年月日是规定日期的年月日
					startYear = _getTimeYear(startDateStamp);
					startMonth = _getTimeMonth(startDateStamp);
					startDay =  _getTimeDay(startDateStamp);
					if(hightLightDate != 0){
						startYear = _getTimeYear(hightLightDate);
						startMonth = _getTimeMonth(hightLightDate);
					}
				}
				this.startYear = startYear;
				this.startMonth = startMonth;
				this.startDay = startDay;
				this.currentYear = startYear;
				this.currentMonth = startMonth;
				this.hightLightDate = hightLightDate;
				this.startDateStamp = startDateStamp;
				this._createDateListData(this.startYear, this.startMonth);
			},

			/**
			 * @method
			 * @desc 创建日历数据 
			 * @param {number} setYear - 当前的年份
			 * @param {number} setMonth - 当前的月份
			 * @var {object[]} dateArr - 每个月的日历数组
			 * @var {number} startWeek - 目标月1号对应的星期几
			 * @var {number} dayNums - 目标月总共有多少天
			 * @var {string} today   - 当月所有的日期
			 * @var {number} stamp   - 日期对应的时间戳
			 * @var {number} dayPrice - 当天的价格数
			 * @var {number} dayStock - 当天的库存数
			 * @var {number} daySold  - 当天的销售数
			 * @var {string} priceTagName - 后台接口价格字段名 
			 * @var {string} stockTagName - 后台接口库存字段名 
			 * @var {string} soldTagName  - 后台接口销量字段名
			 * @var {string} stateTypeName - 后台接口库存状态字段名
			 * @var {string} getFirstDayStatus - 判断是否有库存有效的首天 
			 * @var {string} clazz - 日期对应的类名。 'unavailable' 不可点击、'active' 选中
			 * @var {string} currentDate - 当前日期
			 * @var {number} tempWeek - 当前日对应星期几
			 */
			_createDateListData: function (setYear, setMonth) {
				let dateArr = [];
				let startYear = this.startYear;
				let startMonth = this.startMonth;
				let startDay = 1;
				let startDateStamp = this.startDateStamp;
				let hightLightDate = this.hightLightDate;
				let activeDateIndex = null;
				let startWeek = _getWeek(setYear, setMonth, 1);
				let dayNums = _getTotalDayByMonth(setYear, setMonth);
				let today = '';
				let stamp = '';
				let dayPrice = '';
				let dayStock = '';
				let daySold = '';
				let priceTagName = this.priceTagName;
				let stockTagName = this.stockTagName;
				let soldTagName = this.soldTagName;
				let stateTypeName = this.stateTypeName;
				let getFirstDayStatus = false; 
				if(setYear == _getTimeYear(startDateStamp) && setMonth == _getTimeMonth(startDateStamp )){
					//判断开始遍历的日历是否属于当年当月，不是的情况则为1号，是的情况则为规定时间
					startDay = this.startDay;
				}
				for (let j = -startWeek + 1; j <= dayNums; j++) {
					let clazz = '';
					if((setYear == _getTimeYear(startDateStamp) && setMonth == _getTimeMonth(startDateStamp)&& j<startDay) ){
						//当月规定初始日之前的日期不可选择
						clazz = 'unavailable';
					}
					let tempWeek = -1;
					if (j > 0) {
						tempWeek = _getWeek(setYear, setMonth, j);
						today = _getDateFormat(setYear, setMonth, j);
						stamp = _getTimeStamp(today);
						if(j >= startDay ){
							if(this.priceList.length>0){
								for (let val of this.priceList) {
									//遍历价格日历数组，查找价格库存等信息
									if (val.dateline == stamp) {
											dayPrice = val[priceTagName];
											dayStock = val[stockTagName];
											daySold = val[soldTagName];
											clazz = clazz.replace(/unavailable/, '');
										break;
									} else {
										dayPrice = '';
										dayStock = '';
										daySold = '';
										clazz = 'unavailable';
									}
								}
							}
						}
						if (setYear == _getTimeYear(hightLightDate) && setMonth == _getTimeMonth(hightLightDate) && j == _getTimeDay(hightLightDate)) {
							activeDateIndex = j;
							getFirstDayStatus = true;
						}
					}
					dateArr.push({
						day: j,
						date: today, //日期
						timeStamp: stamp, //时间戳
						class: clazz,
						amount: dayPrice, //价格
						stock: dayStock, //库存
						sold:daySold //销量
					}) 
				}
				this.days = dateArr;
				this.activeDateIndex = activeDateIndex;
			},
	
			/**
			 * @method
			 * @desc 切换上个月。全部时间的月份都是按0~11基准，显示月份才+1
			 * @param {number} year - 年
			 * @param {number} month - 月
			 */
			_lastMonthEvent: function (year,month) {
				this._createDateListData(year, month);
			},
	
			/**
			 * @method
			 * @desc 切换下个月。全部时间的月份都是按0~11基准，显示月份才+1
			 * @param {number} year - 年
			 * @param {number} month - 月
			 */
			_nextMonthEvent: function (year,month) {
				this._createDateListData(year, month);
			},
	
			/**
			 * @method
			 * @desc 选中日期事件
			 * @var {number} year - 年
			 * @var {number} month - 月
			 * @var {number} day - 日
			 * @var {number} amount - 价格
			 * @var {number} stock - 库存
			 * @var {string} dateClass - 每个日期对象的类名
			 */
			_onPressDateEvent: function (e) {
				if(this.canChooseDate){
					let {
						year,
						month,
						day,
						amount,
						stock,
						dateClass
					} = e.currentTarget.dataset;
					//当前选择的日期如果类名含有unavailable，即为不可点击
					if(dateClass.indexOf('unavailable') === -1){
						this._renderRadioPressStyle(year, month, day, amount, stock);
					}
				}
			},
	
			/**
			 * @method
			 * @desc 渲染点击样式(单选),并返回选择的日期对象,对象属性按需求自定义
			 * @param {number} year - 选中的年
			 * @param {number} month - 选中的月
			 * @param {number} day - 选中的日
			 * @param {number} amount - 价格
			 * @param {number} stock - 库存
			 * @property {number} timeStamp - 选中日期的时间戳
			 * @property {number} price - 价格
			 * @property {number} stock - 库存
			 */
			_renderRadioPressStyle:function (year, month, day, amount, stock) {
				let date = _getDateFormat(year,month,day);
				let checkDateObj = this.checkDateObj;
				checkDateObj.day = date;
				checkDateObj.timeStamp = _getTimeStamp(date);
				checkDateObj.price = amount;
				checkDateObj.stock = stock;
				this.activeDateIndex = day
				this.checkDateObj = checkDateObj
				this.$emit('getDateObj',checkDateObj);
			},
		}
	}
</script>

<style lang="scss">
@import 'main';
</style>
